<template>
  <div class="editor-container">
    <div ref="editorElem" class="editor-content"></div>
  </div>
</template>

<script>
// 引入wangEditor
import E from 'wangeditor'

export default {
  name: 'RichTextEditor',
  props: {
    value: {
      type: String,
      default: ''
    },
    placeholder: {
      type: String,
      default: '请输入内容'
    },
    disabled: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      editor: null,
      editorContent: ''
    }
  },
  watch: {
    value: {
      handler(val) {
        if (val !== this.editorContent && this.editor) {
          this.editor.txt.html(val)
        }
      },
      immediate: true
    },
    disabled(val) {
      if (this.editor) {
        this.editor.$textElem.attr('contenteditable', !val)
      }
    }
  },
  mounted() {
    this.initEditor()
  },
  beforeDestroy() {
    // 销毁编辑器
    if (this.editor) {
      this.editor.destroy()
      this.editor = null
    }
  },
  methods: {
    // 格式化文件大小
    formatFileSize(bytes) {
      if (bytes === 0) return '0 B';
      const k = 1024;
      const sizes = ['B', 'KB', 'MB', 'GB'];
      const i = Math.floor(Math.log(bytes) / Math.log(k));
      return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
    },
    
    initEditor() {
      console.log('[RichTextEditor] 初始化富文本编辑器...');
      
      // 创建编辑器实例
      this.editor = new E(this.$refs.editorElem);
      
      // 自定义配置
      this.editor.config.placeholder = this.placeholder;
      this.editor.config.zIndex = 10;
      
      // 配置工具栏
      this.editor.config.menus = [
        'bold',
        'italic',
        'underline',
        'image',
        'code',
        'foreColor',
        'backColor',
        'link',
        'list',
        'justify',
        'quote',
        'undo',
        'redo'
      ];
      
      // 配置图片上传
      const uploadUrl = 'http://localhost:4041/upload/image';
      console.log(`[RichTextEditor] 配置图片上传URL: ${uploadUrl}`);
      
      this.editor.config.uploadImgServer = uploadUrl;
      this.editor.config.uploadFileName = 'image';
      
      const token = this.getToken();
      console.log('[RichTextEditor] 获取到token:', token ? '已设置' : '未设置');
      
      this.editor.config.uploadImgHeaders = {
        'Authorization': `Bearer ${token}`,
        'X-Requested-With': 'XMLHttpRequest'
      };
      
      // 自定义上传图片事件钩子
      this.editor.config.uploadImgHooks = {
        // 图片上传前触发
        before: (file) => {
          console.log('[RichTextEditor] 开始上传图片:', file.name, '大小:', this.formatFileSize(file.size));
          return true; // 返回 true 表示继续上传
        },
        
        // 图片上传并返回结果，自定义上传图片事件
        customInsert: (insertImgFn, result) => {
          console.log('[RichTextEditor] 收到上传响应:', result);
          
          if (result.errno === 0) {
            // 从返回数据中获取图片地址
            const imageUrl = result.data?.url || result.data;
            console.log('[RichTextEditor] 图片上传成功，URL:', imageUrl);
            insertImgFn(imageUrl);
          } else {
            const errorMsg = result.message || '图片上传失败';
            console.error('[RichTextEditor] 图片上传失败:', errorMsg, result);
            this.$message.error(errorMsg);
          }
        },
        
        // 图片上传出错时触发
        error: (xhr, editor, result) => {
          console.error('[RichTextEditor] 图片上传出错:', result);
          this.$message.error('图片上传出错: ' + (result.message || '未知错误'));
        },
        
        // 图片上传超时
        timeout: (xhr) => {
          console.error('[RichTextEditor] 图片上传超时');
          this.$message.error('图片上传超时，请重试');
        },
        
        // 图片上传并返回了错误
        fail: (xhr, editor, result) => {
          console.error('[RichTextEditor] 图片上传失败:', result);
          this.$message.error('图片上传失败: ' + (result?.message || '未知错误'));
        }
      };
      
      // 监听编辑器内容变化
      this.editor.config.onchange = (html) => {
        this.editorContent = html;
        this.$emit('input', html);
        this.$emit('change', html);
        console.log('[RichTextEditor] 内容已更新，长度:', html.length);
      };
      
      // 监听编辑器错误
      this.editor.config.onerror = (error) => {
        console.error('[RichTextEditor] 编辑器错误:', error);
      };
      
      // 创建编辑器
      this.editor.create()
      
      // 初始化内容
      if (this.value) {
        this.editor.txt.html(this.value)
      }
      
      // 设置禁用状态
      if (this.disabled) {
        this.editor.$textElem.attr('contenteditable', !this.disabled)
      }
    },
    
    // 获取token
    getToken() {
      try {
        const user = JSON.parse(localStorage.getItem('user') || '{}');
        return user.token || '';
      } catch (e) {
        return '';
      }
    },
    
    // 获取纯文本内容
    getPlainText() {
      return this.editor ? this.editor.txt.text() : '';
    },
    
    // 获取HTML内容
    getHtml() {
      return this.editor ? this.editor.txt.html() : '';
    },
    
    // 设置内容
    setContent(html) {
      if (this.editor) {
        this.editor.txt.html(html);
      }
    },
    
    // 清空内容
    clear() {
      if (this.editor) {
        this.editor.txt.clear();
      }
    }
  }
}
</script>

<style scoped>
.editor-container {
  width: 100%;
  margin-bottom: 10px;
  position: relative;
}

.editor-content {
  min-height: 150px;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
}

:deep(.w-e-toolbar) {
  border-bottom: 1px solid #dcdfe6 !important;
  background-color: #f5f7fa !important;
}

:deep(.w-e-text-container) {
  border: none !important;
  height: auto !important;
  min-height: 150px !important;
}

:deep(.w-e-menu) {
  z-index: 2 !important;
}

:deep(.w-e-text) {
  padding: 0 10px;
  overflow-y: auto;
}
</style>
